﻿using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.DbEntity.sys;
using Entity.FrameEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Tools;

namespace SysFramework
{
    public class UserManagement:PubMethod
    {
        ReturnResult rsl;
        Commands cmd;
        SystemManagement sysBLL;
        OperateModel oper;

        public UserManagement()
        {
            rsl = new ReturnResult();
            cmd = new Commands();
            sysBLL = new SystemManagement();
            oper = new OperateModel();
        }
        /// <summary>
        /// 获取用户列表(分页)
        /// </summary>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">页面信息条数</param>
        /// <param name="condition">检索条件</param>
        /// <param name="userObj">登录人信息</param>
        /// <param name="pageCount">分页数</param>
        /// <returns></returns>
        public ReturnResult getUserPageList(string pageIndex, string pageSize, string condition,JObject loginUser, ref string pageCount)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0");
                if(loginUser!=null && loginUser["isAdmin"].ToString()!="1")
                {//非管理员人员只显示与己相关账号
                    sb.Append(" and createUser='" + loginUser["userCode"].ToString() + "'");
                }
                string exitFilds = "dept-Dept0";
                sb = CreateSelectCondition(sb, condition, exitFilds);
                var list = cmd.PageList("V_UserInfo", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Data = list;
                rsl.Result = true;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 人员信息同步
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="erpCode"></param>
        /// <returns></returns>
        public ReturnResult SyncUserData(string userCode,string erpCode)
        {
            rsl = new ReturnResult();
         
            var OperList = new List<OperateModel>();
            try
            {
                List<DbUser> userList = new List<DbUser>();
                StringBuilder sb = new StringBuilder();
                #region 同步用户信息

                var erp_User_Table = this.ErpUserData(erpCode);//U8用户信息
                sb.Clear();
                sb.Append("select * from sys_users_info where 1=1 ");
                if (!string.IsNullOrWhiteSpace(erpCode))
                {
                    sb.Append(" and baseCode='" + erpCode + "' ");
                }
                var userTable = cmd.GetDataTable(sb.ToString());//获取所有人员信息
                string defaultPwd = AppSettingHelper.ReadAppSettings("DeafaultPWD");
                if (erp_User_Table.Rows.Count > 0)
                {
                    for (int i = 0; i < erp_User_Table.Rows.Count; i++)
                    {
                        bool isAdd = true;
                        DbUser sys_User = new DbUser();
                        var oper = new OperateModel();
                        var arr = userTable.Select("userCode='" + erp_User_Table.Rows[i]["userCode"].ToString() + "'");
                        if (arr.Length > 0)
                        {
                            isAdd = false;
                        }
                        sys_User.userCode = erp_User_Table.Rows[i]["userCode"].ToString();
                        if (erp_User_Table.Rows[i]["dept"] != null && !string.IsNullOrWhiteSpace(erp_User_Table.Rows[i]["dept"].ToString()))
                        {
                            sys_User.dept = erp_User_Table.Rows[i]["dept"].ToString();
                        }
                        sys_User.userName = erp_User_Table.Rows[i]["userName"].ToString();
                        sys_User.userPhone = erp_User_Table.Rows[i]["uPhone"].ToString();
                        //是否是离职状态 
                        if (erp_User_Table.Rows[i]["nState"].ToString() == "0")
                        {
                            sys_User.status = "Y";
                        }
                        else
                        {
                            sys_User.status = "N";
                        }
                        sys_User.isSync = "Y";
                        if (isAdd)
                        {
                            #region 添加方法
                            sys_User.userPwd = Tools.Encryption.MD5Encode(defaultPwd);
                            sys_User.isAdmin = 0;
                            sys_User.openpwd = defaultPwd;
                            sys_User.isDel = 0;
                            sys_User.baseCode =erpCode;
                            sys_User.createTime = getNow();
                            sys_User.createUser = userCode;
                            oper.Types = OperateModel.OperateType.Add;
                            #endregion
                        }
                        else
                        {
                            #region  修改方法
                            sys_User.isDel = 0;
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Conditions = "userCode";
                            #endregion
                        }
                        oper.Data = sys_User;
                        OperList.Add(oper);

                    }
                }
                #endregion

                rsl = cmd.MoreUpdate(OperList);

            }
            catch (Exception ex)
            {
                rsl.Message = ex.ToString();
            }
            return rsl;
        }
        /// <summary>
        /// erp系统用户数据获取
        /// </summary>
        /// <param name="erpCode"></param>
        /// <returns></returns>
        private DataTable ErpUserData(string erpCode)
        {
            OutBaseHelper cuHelper = new OutBaseHelper();
            StringBuilder sb = new StringBuilder();
            sb.Append("select u.cUser_Id as userCode,u.cUser_Name as userName, ");
            sb.Append(" d.cDepCode as dept,isnull(u.cUserHand,'') as uPhone,u.nState ");
            sb.Append("from ua_user u ");
            sb.Append("left join Department d on u.cDept=d.cDepName");
            return cuHelper.getData(sb.ToString(), erpCode);//U8用户信息
        }
        /// <summary>
        /// 获取部门信息
        /// </summary>
        /// <returns></returns>
        public ReturnResult GetDeptInfo()
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_CommonTree_info where isdel=0  and trType = 'dept' and ");
                sb.Append("parentCode is not null and parentCode!=''");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取人员信息
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult getUserInfoByCode(string userCode, string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from sys_users_info where 1=1");
                if (!string.IsNullOrWhiteSpace(dataId))
                {
                    sb.Append(" and id=" + dataId);
                }
                else if (!string.IsNullOrWhiteSpace(userCode))
                {
                    sb.Append(" and userCode=" + userCode);
                }
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Result = true;
                rsl.Data = cmd.TableToDictionary(table);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.ToString();
            }
            return rsl;
        }
        /// <summary>
        /// 系统用户添加
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <param name=""></param>
        /// <returns></returns>
        public ReturnResult UpdateUser(string jsonStr,string userCode)
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                var user = JsonConvert.DeserializeObject<DbUser>(jsonStr);
                if (string.IsNullOrWhiteSpace(user.userCode))
                {
                    rsl.Message = "登录账号不允许为空";
                    return rsl;
                }
                //if (string.IsNullOrWhiteSpace(user.dept))
                //{
                //    rsl.Message = "部门信息不允许为空";
                //    return rsl;
                //}
                string sql = "select * from sys_users_info where userCode='" + user.userCode + "'";
                var table = cmd.GetDataTable(sql);

                OperateModel oper = new OperateModel();
                List<OperateModel> list = new List<OperateModel>();
                if (user.id != null && user.id > 0)
                {
                    #region 修改数据
                    foreach (DataRow r in table.Rows)
                    {
                        if (r["id"].ToString() != user.id.ToString().Trim())
                        {
                            rsl.Message = string.Format("账号已存在：{0}", user.userCode);
                            return rsl;
                        }
                    }
                    #endregion
                    oper.Data = user;
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    list.Add(oper);
                }
                else
                {
                    var baseCode = sysBLL.getDefaultBaseCode();
                    #region 添加数据
                    if (table.Rows.Count > 0)
                    {
                        rsl.Message = string.Format("账号已存在：{0}", user.userCode);
                        return rsl;
                    }

                    user.status = "Y";
                    user.isSync = "N";
                    user.isAdmin = 0;
                    user.isDel = 0;
                    user.baseCode = baseCode;
                    user.createUser = userCode;
                    user.createTime = DateTime.Now.ToString();
                    user.userPwd =Encryption.MD5Encode(AppSettingHelper.ReadAppSettings("DeafaultPWD").ToString()); 
                    oper.Data = user;
                    oper.Types = OperateModel.OperateType.Add;
                    list.Add(oper);
                    #endregion
                }
                rsl = cmd.MoreUpdate(list);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 重置用户密码
        /// </summary>
        /// <param name="userCode">系统账号</param>
        /// <returns></returns>
        public ReturnResult ReSetPwd(string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(userCode))
                {
                    rsl.Result = false;
                    rsl.Message = "用户账号不能为空";
                    return rsl;
                }
                string sql = "select * from sys_users_info where userCode='" + userCode + "'";
                var table = cmd.GetDataTable(sql);
                if (table.Rows.Count < 1)
                {
                    rsl.Result = false;
                    rsl.Message = "无法获取账号信息";
                    return rsl;
                }
                var pwd = Encryption.MD5Encode(AppSettingHelper.ReadAppSettings("DeafaultPWD").ToString());
                StringBuilder sb = new StringBuilder();
                sb.Append("update  sys_users_info  set  userPwd='" + pwd + "' ");
                sb.Append(" where id=" + table.Rows[0]["id"].ToString() + "");
                rsl = cmd.UpdateSql(sb.ToString());
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="oldpwd"></param>
        /// <param name="newpwd"></param>
        /// <returns></returns>
        public ReturnResult ChanagePWD(string userCode,string oldpwd, string newpwd)
        {
            ReturnResult rsl = new ReturnResult();
            try
            {
                //string enpwd = Tools.Encryption.DesEncrypt(oldpwd);
                //var jmpwd = Tools.Encryption.DesEncrypt(newpwd);

                string enpwd = Encryption.MD5Encode(oldpwd);
                string jmpwd = Encryption.MD5Encode(newpwd);
                string sql = "select * from sys_users_info where userCode='" + userCode + "'";
                var table = cmd.GetDataTable(sql);
                if (table.Rows.Count < 1)
                {
                    rsl.Message = "无法获取账号信息";
                    return rsl;
                }
                if (table.Rows[0]["userPwd"].ToString() != enpwd)
                {
                    rsl.Message = "当前密码输入错误";
                    return rsl;
                }
                sql = "update sys_users_info set userPwd='" + jmpwd + "',openpwd='" + newpwd + "' where userCode='" + userCode + "'";
                rsl = cmd.UpdateSql(sql);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="loginUser"></param>
        /// <returns></returns>
        public ReturnResult DelUserInfo(string userCode,string loginUser)
        {
            rsl = new ReturnResult();
            
            try
            {
                DbUser user = new DbUser();
                user.isDel = 1;
                user.userCode = userCode;
                user.delUser = loginUser;
                user.delTime = getNow();
                oper = new OperateModel();
                oper.Data = user;
                oper.Conditions = "userCode";
                oper.Types = OperateModel.OperateType.Edit;
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 保存人员权限角色
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="groupCode"></param>
        /// <returns></returns>
        public ReturnResult SaveUserRole(string userCode, string groupCode)
        {
            rsl = new ReturnResult();
            try
            {
                DbUser u = new DbUser();
                u.userCode = userCode;
                u.powerRole = groupCode;
                oper = new OperateModel();
                oper.Data = u;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "userCode";
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 清除用户权限
        /// </summary>
        /// <param name="userCode"></param>
        /// <returns></returns>
        public ReturnResult cleanUserRole(string userCode)
        {
            rsl = new ReturnResult();
            try
            {
                DbUser u = new DbUser();
                u.userCode = userCode;
                u.powerRole = "-";
                oper = new OperateModel();
                oper.Data = u;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "userCode";
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 同步部门信息
        /// </summary>
        /// <param name="isAuto"></param>
        /// <returns></returns>
        public ReturnResult SyncDept(string userCode,string baseCode)
        {
            rsl = new ReturnResult();
            OutBaseHelper cuHelper = new OutBaseHelper();
            var OperList = new List<OperateModel>();
            try
            {
                List<DbUser> UserList = new List<DbUser>();
                if (string.IsNullOrWhiteSpace(baseCode))
                {
                    baseCode = sysBLL.getDefaultBaseCode();
                }
                StringBuilder sb = new StringBuilder();
                DbCommonTree sys_dept;
                var deptTable = this.DepartmentDataErp(baseCode);
                sb.Clear();
                sb.Append("select * from fun_CommonTree_info where trType='dept' ");
                var qTable = cmd.GetDataTable(sb.ToString());//获取所有部门信息
                if (qTable.Rows.Count < 1)
                {
                    #region 初始数据 新增一条最顶级菜单
                    sys_dept = new DbCommonTree();
                    sys_dept.trCode = "Dept0";
                    sys_dept.trName = "部门组织";
                    sys_dept.trType = "dept";
                    sys_dept.isSync = "N";
                    sys_dept.isdel = 0;
                    sys_dept.memo = "部门大类";
                    oper=new OperateModel();
                    oper.Data = sys_dept;
                    oper.Types = OperateModel.OperateType.Add;
                    OperList.Add(oper);
                    #endregion
                }
           

                for (int i = 0; i < deptTable.Rows.Count; i++)
                {
                 
                    sys_dept = new DbCommonTree();
                    oper = new OperateModel();
                    var dr = qTable.Select("trCode='" + deptTable.Rows[i]["deptCode"].ToString() + "'");
                    sys_dept.trName = deptTable.Rows[i]["deptName"].ToString();
                    if (string.IsNullOrWhiteSpace(deptTable.Rows[i]["parentCode"].ToString()))
                    {
                        sys_dept.parentCode = "Dept0";
                    }
                    else
                    {
                        sys_dept.parentCode = deptTable.Rows[i]["parentCode"].ToString();
                    }
                  
                    sys_dept.trCode = deptTable.Rows[i]["deptCode"].ToString();
                    sys_dept.baseCode = baseCode;
                    sys_dept.trType = "dept";
                    sys_dept.isSync = "Y";
                    if (deptTable.Rows[i]["leader"] != null && !string.IsNullOrWhiteSpace(deptTable.Rows[i]["leader"].ToString()))
                    {
                        sys_dept.specialFile = deptTable.Rows[i]["leader"].ToString();
                    }
                    if (string.IsNullOrWhiteSpace(deptTable.Rows[i]["fDate"].ToString()))
                    {
                        sys_dept.isdel = 0;
                    }
                    else
                    {
                        sys_dept.isdel = 1;
                    }
                    if (dr.Length > 0)
                    {
                        //修改方法
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "trCode,baseCode,trType";
                    }
                    else
                    {
                        #region  添加
                        sys_dept.createtime = getNow();
                        sys_dept.createuser = userCode;
                        oper.Types = OperateModel.OperateType.Add;
                        #endregion
                    }
                    oper.Data = sys_dept;
                    OperList.Add(oper);
                }
                if (OperList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(OperList);
                }
                else
                {
                    rsl.Message = "没有获取到要同步的数据";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// ERP部门数据信息
        /// </summary>
        /// <returns></returns>
        private DataTable DepartmentDataErp(string baseCode)
        {
            OutBaseHelper cuHelper = new OutBaseHelper();
            StringBuilder sb = new StringBuilder();
            sb.Append("select  cdepcode deptCode,cdepname deptName,idepgrade,dDepEndDate fDate,cDepLeader leader,");
            sb.Append("cDepFullName fullName,'' parentCode from department");
            var table= cuHelper.getData(sb.ToString(), baseCode);
            string parentCode = "dept0";
            #region 根据部门全称找到上级部门编码
            foreach (DataRow r in table.Rows)
            {
                parentCode = "dept0";
                if (!string.IsNullOrWhiteSpace(r["fullName"].ToString()))
                {
                    string parentName = "";
                    if (r["fullName"].ToString().Contains("/"))
                    {
                        var dArr = r["fullName"].ToString().Split('/');
                        parentName = dArr[dArr.Length - 2];
                    }
                    else
                    {
                        parentName = r["fullName"].ToString();
                    }
                    if (parentName != r["deptName"].ToString())
                    {
                        var qdr = table.Select("deptName='" + parentName + "'");
                        if (qdr.Length > 0)
                        {
                            parentCode = qdr[0]["deptCode"].ToString();
                        }
                    }
                }
                r.BeginEdit();
                r["parentCode"]=parentCode;
                r.EndEdit();
            }
            #endregion
            return cuHelper.getData(sb.ToString(), baseCode);//U8部门信息
        }
        public ReturnResult GetUserInfo()
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb=new StringBuilder();
                sb.Append("select userCode,userName from sys_users_info where status='Y' and isdel=0");
                var uTable = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(uTable);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }
}
